import 'dart:convert';

import 'package:family_expense/shared/models/system_setting.dart';
import 'package:my_flutter_core/my_flutter_core.dart';

class SystemSettingService {
  // Cached setting which loaded from local.
  static SystemSetting? _systemSetting;

  /// Gets current system setting. If the cached setting does not exist we need to load it from local.
  static Future<SystemSetting> get setting async {
    // Tries to load from local storage.
    if (_systemSetting == null) {
      await _loadSetting();
    }

    // If loaded data is null then creates a default one.
    _systemSetting ??= SystemSetting();

    return _systemSetting!;
  }

  /// Saves the [setting] on local and cache it.
  static Future<void> saveSetting(SystemSetting setting) async {
    // Updates the cached setting.
    _systemSetting = setting;

    // Converts the [setting] to json format.
    final settingInfo = setting.toFlatJson();

    // Encodes the json data to json format string.
    final encodedData = json.encode(settingInfo);

    await LocalStorage.set<String>(
      GeneralConfig.localSystemSettingStorageKey,
      encodedData,
    );
  }

  /// Loads setting from local and cache it.
  static Future<void> _loadSetting() async {
    // Loads the token data from local with string format.
    final settingString = await LocalStorage.get<String>(
      GeneralConfig.localSystemSettingStorageKey,
    );

    if (settingString.isNotNullOrEmpty) {
      // Decodes the string to json object.
      final settingDecoded = json.decode(settingString!);

      // Sets the [_token] property.
      _systemSetting = SystemSetting.fromFlatJson(settingDecoded);
    }
  }
}
